package com.web.quartz;

import com.web.farme.tool.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

/**
 * @author: bi
 * @date: 2022/4/21 14:21
 */
@Slf4j
public class ScheduleUtils {

    public static void createJob(Scheduler scheduler, ScheduleJob job) {

        ScheduleBuilder<?> scheduleBuilder;
        if (StringUtils.isNotBlank(job.getCronExpression())) {
            scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
        } else {
            scheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
        }
        boolean isSync = job.isSync();
        Class<? extends Job> aClass = isSync ? SyncJob.class : AsyncJob.class;
        JobDetail jobDetail = JobBuilder.newJob(aClass).withIdentity(job.getJobName(), job.getJobGroup()).build();
        jobDetail.getJobDataMap().put(QuartzConstants.JOB_KEY, job);

        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity(job.getJobName(), job.getJobGroup())
                .withSchedule(scheduleBuilder)
                .startNow()
                .build();
        try {
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            log.info("定时任务创建失败" + e.getMessage(), e);
        }
    }
}
